package com.cityguardian.cityguardianapp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.cityguardian.utils.Utils;
import com.cityguardian.ws.ConnectionThread;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;

public class AsyncTaskRegistroGCM extends AsyncTask<String,Integer,String>{
	
	private static final String PROPERTY_REG_ID = "registration_id";
	private static final String PROPERTY_APP_VERSION = "appVersion";
	private static final String PROPERTY_EXPIRATION_TIME = "onServerExpirationTimeMs";
	private static final String PROPERTY_USER = "user";
	private static final Long EXPIRATION_TIME_MS = (long) (1000 * 3600 * 24 * 7);
	private static final String TAG = "TAG";
	private GoogleCloudMessaging gcm;
	private String regid;
	private Context context;
	
	public AsyncTaskRegistroGCM(GoogleCloudMessaging gcm, String regid, Context context){
		this.gcm = gcm;
		this.regid = regid;
		this.context = context;
		//this.activity=mainActivity;
	}
	
	
    @Override
    protected String doInBackground(String... params)
    {
            String msg = "";
 
            try
            {
                if (gcm == null)
                {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
 
                //Nos registramos en los servidores de GCM
                regid = gcm.register(Utils.SENDER_ID);
 
                Log.d(TAG, "Registrado en GCM: registration_id=" + regid);
                
                List<NameValuePair> param = new ArrayList<NameValuePair>();								
        		param.add(new BasicNameValuePair("iduser", params[0]));
        		param.add(new BasicNameValuePair("regid", regid));
        		String route="/ws/GcmAdapter/registerID/";
        		
        		ConnectionThread connection = new ConnectionThread(param, route);
        		//TODO FIJATE SI ES MEJOR PASAR LOS PARAMETROS EN EL GETRESPONSE
        		String responseBody = connection.getResponse();
        		
        		if (responseBody==null){
        			Log.e("log_tag", "Error in webservice");
        			return null;
        		}
        		else{
        			Log.d("GCM",responseBody);
        			if (responseBody.equals("1")){
        				setRegistrationId(context, params[0], regid);
        			}
        		}
                
                //Nos registramos en nuestro servidor
//                boolean registrado = registroServidor(params[0], regid);
//                
//                //Guardamos los datos del registro
//                if(registrado)
//                {
//                    setRegistrationId(context, params[0], regid);
//                }
            }
            catch (IOException ex)
            {
                Log.d(TAG, "Error registro en GCM:" + ex.getMessage());
            }
 
            return msg;
    }
    
    private void setRegistrationId(Context context, String user, String regId)
    {
        SharedPreferences prefs = context.getSharedPreferences(
        MainActivity.class.getSimpleName(),
            Context.MODE_PRIVATE);
     
        int appVersion = Utils.getAppVersion(context);
     
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_USER, user);
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.putLong(PROPERTY_EXPIRATION_TIME,
        System.currentTimeMillis() + EXPIRATION_TIME_MS);
     
        editor.commit();
    }

}
